package ua.org.nuos.sdms.clientgui.client.view.selectGroup;

import com.vaadin.data.Item;
import com.vaadin.data.Validator;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.factory.*;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.SearchGroupEvent;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.clientgui.server.validators.EmailValidator;
import ua.org.nuos.sdms.middle.vo.GroupSearch;

import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 04.03.12
 * Time: 17:05
 * To change this template use File | Settings | File Templates.
 */
public class SearchGroupComponent extends VerticalLayout {

    public static final String ID = SearchGroupComponent.class.getSimpleName();

    private BeanItem<GroupSearch> searchBeanItem;
    private Form form;
    private Layout mainLayout;

    public SearchGroupComponent() {
        this.mainLayout = this;
        init();
    }

    private void init() {
        setSizeFull();
        AppProxy.getInstance().getComponentLocator().addContainer(ID, this);

        AppProxy.getInstance().getComponentLocator().getWindow(SelectGroupWindow.ID)
                .addWindowCloseListener(new Window.CloseListener() {
            @Override
            public void windowClose(Window.CloseEvent e) {
                AppProxy.getInstance().getModelLocator().setGroupSearch(null);
            }
        });
        if (AppProxy.getInstance().getModelLocator().getGroupSearch() == null) {
            AppProxy.getInstance().getModelLocator().setGroupSearch(new GroupSearch());
        }
        searchBeanItem = new BeanItem<GroupSearch>(AppProxy.getInstance().getModelLocator().getGroupSearch());
        form = new Form() {

            public void setVisibleItemProperties(Collection<?> visibleProperties) {
                super.getLayout().removeAllComponents();
                super.setVisibleItemProperties(visibleProperties);
            }

            protected void attachField(Object propertyId, Field field) {
                super.attachField(propertyId, field);
                if (propertyId.equals("organisationName")) {
                    getLayout().addComponent(SeparatorFactory.getHorizontal());
                }
            }
        };
        form.setFormFieldFactory(new FieldFactory());
        form.setItemDataSource(searchBeanItem);
        form.setVisibleItemProperties(Arrays.asList(new String[]{"groupName", "organisationName", "userName", "userEmail"}));
        form.setSizeFull();

        Layout buttons = getButtonsLayout();

        mainLayout = new VerticalLayout();
        mainLayout.setSizeFull();
        addComponent(form);
        addComponent(buttons);
        setComponentAlignment(buttons, Alignment.BOTTOM_RIGHT);
    }

    private Layout getButtonsLayout() {
        Button close = WindowFactory.getCloseButton(
                AppProxy.getInstance().getComponentLocator().getWindow(SelectGroupWindow.ID).getWindow(), "Не стоит");
        Button register = ButtonFactory.getButton("Искать группу", getSearchClickListener());
        return LayoutFactory.getHLayout(register, close);
    }

    private Button.ClickListener getSearchClickListener() {
        return new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    form.commit();
                    AppProxy.getInstance().getModelLocator().setGroupSearch(searchBeanItem.getBean());
                    AppProxy.getInstance().getController(GlobalBoard.ID).fire(new SearchGroupEvent());
                } catch (Validator.InvalidValueException e) {
                    Logger.getAnonymousLogger().log(Level.WARNING, "validation exception", e);
                }
            }
        };
    }

    class FieldFactory extends CustomFieldFactory {
        @Override
        public Field createField(Item item, Object propertyId, Component uiContext) {
            Field f = super.createField(item, propertyId, uiContext);
            if (propertyId.equals("groupName")) {
                f = createTextField("Название группы", false);
            } else if (propertyId.equals("organisationName")) {
                f = createTextField("Организация", false);
            } else if (propertyId.equals("userName")) {
                f = createTextField("Имя учасника группы", false);
            } else if (propertyId.equals("userEmail")) {
                f = createTextField("Email учасника группы", false);
                f.addValidator(new EmailValidator("Введённый Email неверен."));
            }
            return f;
        }
    }
}
